package nsq

import (
	"github.com/golang/glog"
	nsq "github.com/nsqio/go-nsq"
)

// ReceiverEnv nsq receiver init params
type ReceiverEnv struct {
	Address string
	Config  *nsq.Config
	Topic   string
	Channel string
	Handler *nsq.Handler
}

// Receiver receiver publish interface
type Receiver interface {
	Init(*ReceiverEnv) error // init function
}

type receive struct{}

// NewReceive receiver new function
func NewReceive() Receiver {
	return new(receive)
}

func (p *receive) Init(env *ReceiverEnv) error {
	consumer, err1 := nsq.NewConsumer(env.Topic, env.Channel, env.Config) // init consumer
	if err1 != nil {
		glog.Fatalf("nsq consumer create fail: %v", err1)
		return err1
	}
	consumer.AddHandler(*env.Handler) // add consumer handler interface

	if err2 := consumer.ConnectToNSQLookupd(env.Address); err2 != nil { // setup nsqlookupd connect
		glog.Fatalf("nsq connect to nsqlookupd fail: %v", err1)
		return err2
	}
	return nil
}
